package com.spzx.order.receiver;


import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.order.configure.DeadLetterMqConfig;
import com.spzx.order.configure.DelayedMqConfig;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @Author ChenXing
 * @Description 测试消费端 可以在此建立 交换机和消息队列
 * @Create 2024/8/16 19:27
 */

@Slf4j
@Component
public class TestReceiver {


    /***
     * 监听延迟队列
     */
    @SneakyThrows
    @RabbitListener(queues =  DelayedMqConfig.queue_delay_1)
    public void c(Message message, String msg, Channel channel)
    {
        System.out.println("监听延迟队列.......");
        try {
            log.info("TestReceiver:a收到的消息：{}", message);
            log.info("TestReceiver:a收到的消息：{}", msg);
            // 手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);// 默认非批量确认
        }catch (Exception e){
            // 消息消费失败
            // 回滚消息,退回消息队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }

    /***
     * 监听死信队列
     */
    @SneakyThrows
    @RabbitListener(queues =  DeadLetterMqConfig.queue_dead_2)
    public void b(Message message, String msg, Channel channel)
    {
        System.out.println("监听死信队列.......");
        try {
            log.info("TestReceiver:a收到的消息：{}", message);
            log.info("TestReceiver:a收到的消息：{}", msg);
            // 手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);// 默认非批量确认
        }catch (Exception e){
            // 消息消费失败
            // 回滚消息,退回消息队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TEST, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_TEST, durable = "true"),
            key = MqConst.ROUTING_TEST
    ))
    public void test(String content, Message message, Channel channel) {
        try {
            //都可以
            log.info("接收消息：{}", content);
            log.info("接收消息：{}", new String(message.getBody()));

            // 手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);// 默认非批量确认

        }catch (Exception e ){

            // 消息消费失败
            // 回滚消息返回消息队列中
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);

        }
    }





}
